package app.beit.finportal.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import app.beit.finportal.entity.Menu;

public class MenuDao {

	@Autowired
	private SessionFactory sessionFactory;
	
	@SuppressWarnings("unchecked")
	public List<Menu> getAllMenu() throws Exception{
		final Session session = this.sessionFactory.openSession();
		final List<Menu> result = session.createQuery("from Menu m order by sort_by").list();
		session.close();
		
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public List<Menu> getAllActiveMenu() throws Exception{
		final Session session = this.sessionFactory.openSession();
		final List<Menu> result = session.createQuery("from Menu m where is_active='Y' order by sort_by").list();
		session.close();
		
		return result;
	}
	
	public Menu getById(final String id) throws Exception{
		final Session session = this.sessionFactory.openSession();
		final Menu result = (Menu) session.createQuery("from Menu n where id='" + id + "' ").uniqueResult();
		session.close();
		
		return result;
	}
	
	public boolean updateListMenu(final List<Menu> entities){
		final Session session = this.sessionFactory.openSession();
		final Transaction tr = session.beginTransaction();
		try{
			for(Menu m : entities){
				session.update(m);
			}
			tr.commit();
			session.close();
		}catch(Exception e){
			tr.rollback();
			session.close();
			return false;
		}
		return true;
	}
}
